package org.example;

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Grammar grammar = new Grammar();

        //添加终结符
        grammar.addTerminal("id");
        grammar.addTerminal("+");
        grammar.addTerminal("-");
        grammar.addTerminal("*");
        grammar.addTerminal("/");
        grammar.addTerminal("(");
        grammar.addTerminal(")");
        grammar.addTerminal("ε");
        grammar.addTerminal("$");

        //添加非终结符
        grammar.addNonTerminal("E");
        grammar.addNonTerminal("E'");
        grammar.addNonTerminal("T");
        grammar.addNonTerminal("T'");
        grammar.addNonTerminal("F");

        //设置开始符号
        grammar.setStartSymbol("E");

        //添加产生式
        grammar.addProduction(new Production("E", Arrays.asList("T","E'")));
        grammar.addProduction(new Production("E'",Arrays.asList("+","T","E'")));
        grammar.addProduction(new Production("E'",Arrays.asList("-","T","E'")));
        grammar.addProduction(new Production("E'",Arrays.asList("ε")));
        grammar.addProduction(new Production("T",Arrays.asList("F","T'")));
        grammar.addProduction(new Production("T'",Arrays.asList("*","F","T'")));
        grammar.addProduction(new Production("T'",Arrays.asList("/","F","T'")));
        grammar.addProduction(new Production("T'",Arrays.asList("ε")));
        grammar.addProduction(new Production("F",Arrays.asList("(","E",")")));
        grammar.addProduction(new Production("F",Arrays.asList("id")));


        LL1Parser parser = new LL1Parser(grammar);
//        List<String> input = Arrays.asList("id", "+", "id");
        List<String> input = Arrays.asList("(", "id", "+", "id", ")", "*", "id");
        boolean result = parser.parse(input);

        // 输出表格
        System.out.println("LL(1)解析过程表:");
        System.out.printf("%-6s | %-25s | %-25s | %-30s%n",
                "步骤", "栈", "剩余输入符号串", "所用产生式");
        System.out.println("---------------------------------------------------------------------------------------------------");

        for (ParsingStep step : parser.getSteps()) {
            System.out.printf("%-6d | %-25s | %-25s | %-30s%n",
                    step.stepNumber, step.stack, step.input, step.production);
        }

        System.out.println("\n解析结果: " + (result ? "成功" : "失败"));

        // 输出错误信息
        System.out.println("\n错误信息:");
        if(parser.getErrorMessages().size()==0){
            System.out.println("没有错误信息");
        }
        for (String error : parser.getErrorMessages()) {
            System.out.println("- " + error);
        }




    }
}